package com.java46.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.java46.entity.GenericResultEntity;
import com.java46.entity.MessageBoard;
import com.java46.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName MessageController
 * @Description 留言板功能
 * @Author Tigger Wu
 * @Date 2018/8/2110:21
 * @Version 1.0
 **/
@Controller
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;
    /**
     *  分页查询
     *
     * @author Tigger Wu
     * @date 2018/8/21 10:25
     * @param  page, request, model
     * @return java.lang.String
     */
    @RequestMapping(value = "/queryList" ,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryList(Integer page, HttpServletRequest request, Model model) throws JsonProcessingException {
        //将数据放入分页信息中
        PageInfo<MessageBoard>minfo = messageService.queryMessage(page);
        //创建结果实体并赋值
        GenericResultEntity result = new GenericResultEntity();
        result.setSuccess(true);
        result.setData(minfo);
        //参数map
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("messages",result);
        //转为json
        ObjectMapper mapper= new ObjectMapper();
        String jsonStr =  mapper.writeValueAsString(map);
        return jsonStr;
    }

    /**
     *  添加信息
     *
     * @author Tigger Wu
     * @date 2018/8/21 10:27
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addMessage",produces = "application/json;charset=utf-8")
    public String addMessage(MessageBoard messageBoard) throws JsonProcessingException {
        List<String> vlist = new ArrayList<String>();
        try {
            //获取留言时间
            Date mestime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //设置留言时间和留言状态
            messageBoard.setMesdate(sdf.format(mestime));
            messageBoard.setMesstate("0");
            messageService.addMessage(messageBoard);
            vlist.add("操作成功！");
        }catch (RuntimeException e){
            vlist.add("数据异常，请稍后再试！");
            throw new RuntimeException(e);
        }
        // 2. 创建 ObjectMapper 对象
        ObjectMapper mapper= new ObjectMapper();
        //创建json字符串接收数据
        String jsonStr =  mapper.writeValueAsString(vlist);
        return jsonStr;
    }
}
